// 知识库管理相关功能

// 全局变量
// 使用window.currentKnowledgeBaseId从index-main.js中引用
let currentKnowledgeBaseName = '';
let currentDocumentId = null;
let isEditMode = false;
let currentInputMethod = 'text';
let uploadedFileInfo = null;

// 显示通知
function showNotification(message, type = 'success') {
    const notification = document.getElementById('notification');
    
    // 设置通知类型样式
    notification.className = 'notification';
    if (type === 'error') {
        notification.classList.add('notification-error');
    } else if (type === 'warning') {
        notification.classList.add('notification-warning');
    } else {
        notification.classList.add('notification-success');
    }
    
    notification.textContent = message;
    notification.style.transform = 'translateX(0)';
    
    setTimeout(() => {
        notification.style.transform = 'translateX(150%)';
    }, 3000);
}

// 加载知识库列表
async function loadKnowledgeBases() {
    try {
        const token = localStorage.getItem('token');
        if (!token) {
            showNotification('您需要登录才能查看知识库');
            return;
        }
        
        const response = await fetch('/api/knowledge-base/list', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (response.ok) {
            const data = await response.json();
            displayKnowledgeBases(data);
        } else {
            console.error('获取知识库列表失败');
            document.getElementById('knowledge-list').innerHTML = 
                '<div class="error-message">获取知识库列表失败</div>';
        }
    } catch (error) {
        console.error('加载知识库错误:', error);
        document.getElementById('knowledge-list').innerHTML = 
            '<div class="error-message">加载知识库时出错，请重试</div>';
    }
}

// 显示知识库列表
function displayKnowledgeBases(knowledgeBases) {
    const container = document.getElementById('knowledge-list');
    
    if (knowledgeBases.length === 0) {
        container.innerHTML = `
            <div class="empty-placeholder">
                <i class="bi bi-book"></i>
                <p>暂无知识库</p>
                <p class="hint">点击"新建知识库"创建您的第一个知识库</p>
            </div>
        `;
        return;
    }
    
    // 清空容器
    container.innerHTML = '';
    
    // 添加知识库项
    knowledgeBases.forEach(kb => {
        const kbItem = document.createElement('div');
        kbItem.className = 'kb-item';
        kbItem.innerHTML = `
            <div class="kb-item-header">
                <i class="bi bi-book"></i>
                <h3>${escapeHtml(kb.name)}</h3>
            </div>
            <p class="kb-description">${escapeHtml(kb.description || '暂无描述')}</p>
            <div class="kb-meta">
                <span><i class="bi bi-files"></i>${kb.fileCount || 0} 文件</span>
                <span><i class="bi bi-clock"></i>${formatDate(kb.updateTime || kb.createTime)}</span>
            </div>
            <div class="kb-actions">
                <button class="kb-action-btn" onclick="openKnowledgeBase('${kb.id}')">
                    <i class="bi bi-chat-text"></i>
                    <span>对话</span>
                </button>
                <button class="kb-action-btn" onclick="manageKnowledgeBase('${kb.id}', event)">
                    <i class="bi bi-gear"></i>
                    <span>管理</span>
                </button>
            </div>
        `;
        container.appendChild(kbItem);
    });
}

// 查看知识库文档列表
async function viewKnowledgeBase(kbId, kbName) {
    console.log("查看知识库:", kbId, kbName);
    
    // 设置全局变量
    window.currentKnowledgeBaseId = kbId;
    currentKnowledgeBaseName = kbName;
    
    // 更新UI显示的知识库名称
    const nameElement = document.getElementById('current-kb-name-docs');
    if (nameElement) {
        nameElement.textContent = kbName || '文档管理';
    }
    
    // 隐藏所有panel
    document.querySelectorAll('.tab-panel').forEach(panel => {
        panel.classList.remove('active');
    });
    
    // 显示文档管理panel
    const docsSection = document.getElementById('docs-section');
    if (docsSection) {
        docsSection.classList.add('active');
        console.log("成功切换到文档管理面板");
    } else {
        console.error("未找到文档管理面板元素");
        showNotification("无法查看知识库文档", "error");
    }
    
    // 传递特定的kbId，不要使用window.currentKnowledgeBaseId
    loadDocuments(kbId);
}

// 加载文档列表
async function loadDocuments(knowledgeBaseId) {
    try {
        // 如果传入的knowledgeBaseId为空，则使用全局变量
        if (!knowledgeBaseId && window.currentKnowledgeBaseId) {
            knowledgeBaseId = window.currentKnowledgeBaseId;
        }
        
        // 如果仍然没有knowledgeBaseId，显示错误并返回
        if (!knowledgeBaseId) {
            showNotification('没有选择知识库，无法加载文档', 'error');
            return;
        }
        
        // 显示加载动画
        showDocsLoading();
        
        const token = localStorage.getItem('token');
        if (!token) {
            showNotification('您需要登录才能查看文档');
            hideDocsLoading();
            return;
        }
        
        const response = await fetch(`/api/document/list?knowledgeBaseId=${knowledgeBaseId}`, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (!response.ok) {
            throw new Error('加载文档失败');
        }
        
        const data = await response.json();
        displayDocuments(data);
    } catch (error) {
        console.error('加载文档失败:', error);
        showNotification('加载文档失败', 'error');
    } finally {
        // 隐藏加载动画
        hideDocsLoading();
    }
}

// 显示加载动画
function showDocsLoading() {
    const container = document.getElementById('documents-list');
    
    // 创建加载动画元素
    const loadingElement = document.createElement('div');
    loadingElement.className = 'docs-loading';
    loadingElement.innerHTML = `
        <div class="docs-loading-spinner"></div>
        <div class="docs-loading-text">加载文档中...</div>
    `;
    
    // 添加到容器
    container.appendChild(loadingElement);
}

// 隐藏加载动画
function hideDocsLoading() {
    const loadingElement = document.querySelector('.docs-loading');
    if (loadingElement) {
        loadingElement.remove();
    }
}

// 显示文档列表
function displayDocuments(documents) {
    const container = document.getElementById('documents-list');
    
    if (!documents || documents.length === 0) {
        container.innerHTML = `
            <div class="empty-placeholder">
                <i class="bi bi-file-earmark-text"></i>
                <p>暂无文档</p>
                <p class="hint">点击"添加文档"添加第一个文档</p>
            </div>
        `;
        // 确保容器有正确的样式
        container.style.display = 'block';
        container.style.gridTemplateColumns = 'none';
        return;
    }
    
    // 清空容器
    container.innerHTML = '';
    
    // 确保容器有正确的网格样式
    container.style.display = 'grid';
    container.style.gridTemplateColumns = 'repeat(auto-fill, minmax(280px, 1fr))';
    
    // 直接使用container作为文档列表容器
    documents.forEach(doc => {
        const fileName = doc.fileName || '';
        const fileExtension = fileName.split('.').pop().toLowerCase();
        let previewText = doc.content || '无预览内容';
        // 限制预览文本长度为100个字符
        if (previewText.length > 100) {
            previewText = previewText.substring(0, 100) + '...';
        }
        
        // 根据文件类型设置图标和类型标签
        let fileIcon = 'bi-file-text';
        let fileType = '文档';
        let bgColor = '#4361ee'; // 默认蓝色
        
        if (fileExtension === 'pdf') {
            fileIcon = 'bi-file-earmark-pdf';
            fileType = 'PDF';
            bgColor = '#ef4444'; // 红色
        } else if (['doc', 'docx'].includes(fileExtension)) {
            fileIcon = 'bi-file-earmark-word';
            fileType = 'Word';
            bgColor = '#0ea5e9'; // 蓝色
        } else if (['xls', 'xlsx'].includes(fileExtension)) {
            fileIcon = 'bi-file-earmark-excel';
            fileType = 'Excel';
            bgColor = '#10b981'; // 绿色
        } else if (['ppt', 'pptx'].includes(fileExtension)) {
            fileIcon = 'bi-file-earmark-powerpoint';
            fileType = 'PPT';
            bgColor = '#f97316'; // 橙色
        } else if (['txt', 'md'].includes(fileExtension)) {
            fileIcon = 'bi-file-earmark-text';
            fileType = '文本';
            bgColor = '#6366f1'; // 靛蓝色
        } else if (['jpg', 'jpeg', 'png', 'gif'].includes(fileExtension)) {
            fileIcon = 'bi-file-earmark-image';
            fileType = '图片';
            bgColor = '#8b5cf6'; // 紫色
        }
        
        const docItem = document.createElement('div');
        docItem.className = 'doc-item';
        docItem.dataset.id = doc.id;
        docItem.addEventListener('click', (e) => {
            // 防止点击按钮时触发查看文档
            if (!e.target.closest('.doc-action-btn')) {
                viewDocument(doc.id);
            }
        });
        
        // 计算创建时间的相对时间
        const relativeTime = getRelativeTimeString(new Date(doc.createTime));
        
        docItem.innerHTML = `
            <div class="doc-header">
                <div class="doc-icon" style="background-color: ${bgColor}15; color: ${bgColor};">
                    <i class="bi ${fileIcon}"></i>
                </div>
                <div class="doc-info">
                    <div class="doc-name" title="${escapeHtml(fileName || doc.title || '未命名文档')}">${escapeHtml(doc.title || fileName || '未命名文档')}</div>
                    <div class="doc-meta">
                        <span title="${formatDate(doc.createTime)}"><i class="bi bi-clock"></i> ${relativeTime}</span>
                        <span class="doc-type-badge" style="background-color: ${bgColor}15; color: ${bgColor};">${fileType}</span>
                    </div>
                </div>
            </div>
            <div class="doc-preview">${escapeHtml(previewText)}</div>
            <div class="doc-actions">
                <button class="doc-action-btn view-btn" onclick="event.stopPropagation(); viewDocument('${doc.id}')" title="查看文档">
                    <i class="bi bi-eye"></i> 查看
                </button>
                <button class="doc-action-btn edit-btn" onclick="event.stopPropagation(); editDocument('${doc.id}', event)" title="编辑文档">
                    <i class="bi bi-pencil"></i> 编辑
                </button>
                <button class="doc-action-btn delete-btn" onclick="event.stopPropagation(); deleteDocument('${doc.id}', event)" title="删除文档">
                    <i class="bi bi-trash"></i> 删除
                </button>
            </div>
        `;
        
        container.appendChild(docItem);
    });
}

// 查看文档内容
function viewDocument(docId) {
    console.log("尝试查看文档:", docId, "当前知识库ID:", window.currentKnowledgeBaseId);
    
    if (!window.currentKnowledgeBaseId) {
        showNotification('请先选择或创建知识库', 'warning');
        return;
    }
    
    showLoading();
    
    const token = localStorage.getItem('token');
    if (!token) {
        showNotification('您需要登录才能查看文档', 'warning');
        hideLoading();
        return;
    }
    
    fetch(`/api/document/${docId}`, {
        headers: {
            'Authorization': `Bearer ${token}`
        }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('获取文档失败');
        }
        return response.json();
    })
    .then(doc => {
        console.log("获取到文档数据:", doc);
        
        // 显示文档内容界面
        document.querySelectorAll('.tab-panel').forEach(panel => {
            panel.classList.remove('active');
        });
        
        const docContentSection = document.getElementById('doc-content-section');
        console.log("文档内容区域元素:", docContentSection);
        
        if (docContentSection) {
            docContentSection.classList.add('active');
            
            // 更新文档标题和元数据
            const docTitle = document.getElementById('current-doc-title');
            if (docTitle) {
                docTitle.textContent = doc.title || doc.fileName || '未命名文档';
            } else {
                console.error("未找到文档标题元素");
            }
            
            // 确定文档类型图标
            let fileIcon = 'bi-file-text';
            let docTypeLabel = '文本文档';
            
            if (doc.fileName) {
                const fileExt = doc.fileName.split('.').pop().toLowerCase();
                
                if (['pdf'].includes(fileExt)) {
                    fileIcon = 'bi-file-earmark-pdf';
                    docTypeLabel = 'PDF文档';
                } else if (['doc', 'docx'].includes(fileExt)) {
                    fileIcon = 'bi-file-earmark-word';
                    docTypeLabel = 'Word文档';
                } else if (['xls', 'xlsx'].includes(fileExt)) {
                    fileIcon = 'bi-file-earmark-excel';
                    docTypeLabel = 'Excel文档';
                } else if (['ppt', 'pptx'].includes(fileExt)) {
                    fileIcon = 'bi-file-earmark-slides';
                    docTypeLabel = 'PPT文档';
                } else if (['txt'].includes(fileExt)) {
                    fileIcon = 'bi-file-earmark-text';
                    docTypeLabel = '文本文件';
                } else if (['jpg', 'jpeg', 'png', 'gif'].includes(fileExt)) {
                    fileIcon = 'bi-file-earmark-image';
                    docTypeLabel = '图片';
                }
            }
            
            // 处理文档内容
            const contentContainer = document.getElementById('document-content');
            if (!contentContainer) {
                console.error("未找到文档内容容器元素");
                return;
            }
            
            // 处理不同类型的文档内容
            if (doc.fileName) {
                const fileExt = doc.fileName.split('.').pop().toLowerCase();
                
                // 为特定类型的文件提供适当的视图
                if (['jpg', 'jpeg', 'png', 'gif'].includes(fileExt) && doc.fileUrl) {
                    // 图片文件，显示图片
                    contentContainer.innerHTML = `
                        <div class="image-preview">
                            <img src="${doc.fileUrl}" alt="${escapeHtml(doc.title || doc.fileName)}" />
                        </div>
                        <div class="doc-text-content">${marked.parse(doc.content || '')}</div>
                    `;
                } else if (['pdf'].includes(fileExt) && doc.fileUrl) {
                    // PDF文件，提供预览或下载链接
                    contentContainer.innerHTML = `
                        <div class="file-action-buttons">
                            <a href="${doc.fileUrl}" target="_blank" class="btn-primary">
                                <i class="bi bi-eye"></i> 查看PDF
                            </a>
                            <a href="${doc.fileUrl}" download="${doc.fileName}" class="btn-secondary">
                                <i class="bi bi-download"></i> 下载文件
                            </a>
                        </div>
                        <div class="doc-text-content">${marked.parse(doc.content || '')}</div>
                    `;
                } else {
                    // 其他文件，展示解析的内容，提供下载链接
                    let downloadLink = '';
                    if (doc.fileUrl) {
                        downloadLink = `
                            <div class="file-action-buttons">
                                <a href="${doc.fileUrl}" download="${doc.fileName}" class="btn-secondary">
                                    <i class="bi bi-download"></i> 下载原始文件
                                </a>
                            </div>
                        `;
                    }
                    
                    contentContainer.innerHTML = `
                        ${downloadLink}
                        <div class="doc-text-content">${marked.parse(doc.content || '')}</div>
                    `;
                }
            } else {
                // 普通文本/Markdown 文档
                contentContainer.innerHTML = marked.parse(doc.content || '');
            }
            
            // 添加文档创建时间等元数据
            const metadataElement = document.getElementById('document-metadata');
            if (metadataElement) {
                let fileInfoHtml = '';
                if (doc.fileName) {
                    fileInfoHtml = `
                        <div class="doc-meta-item">
                            <i class="bi bi-file-earmark"></i> 
                            文件名称: ${escapeHtml(doc.fileName)}
                        </div>
                        <div class="doc-meta-item">
                            <i class="bi bi-tag"></i> 
                            文件类型: ${docTypeLabel}
                        </div>
                    `;
                    
                    if (doc.fileSize) {
                        fileInfoHtml += `
                            <div class="doc-meta-item">
                                <i class="bi bi-hdd"></i> 
                                文件大小: ${formatFileSize(doc.fileSize)}
                            </div>
                        `;
                    }
                }
                
                metadataElement.innerHTML = `
                    <div class="doc-meta-item">
                        <i class="bi bi-calendar-plus"></i> 
                        创建于: ${new Date(doc.createTime).toLocaleString()}
                    </div>
                    ${doc.updateTime && doc.updateTime !== doc.createTime ? 
                    `<div class="doc-meta-item">
                        <i class="bi bi-calendar-check"></i> 
                        更新于: ${new Date(doc.updateTime).toLocaleString()}
                    </div>` : ''}
                    ${fileInfoHtml}
                `;
            } else {
                console.error("未找到文档元数据元素");
            }
            
            // 添加文档操作按钮
            const actionsElement = document.getElementById('document-actions');
            if (actionsElement) {
                actionsElement.innerHTML = `
                    <button class="edit-doc-btn" onclick="editDocument('${docId}', event)">
                        <i class="bi bi-pencil-square"></i>
                        <span>编辑文档</span>
                    </button>
                    <button class="delete-doc-btn" onclick="deleteDocument('${docId}', event, true)">
                        <i class="bi bi-trash"></i>
                        <span>删除文档</span>
                    </button>
                `;
            } else {
                console.error("未找到文档操作按钮容器元素");
            }
        } else {
            console.error("未找到文档内容区域元素");
            showNotification("加载文档详情失败，找不到详情面板", "error");
        }
        
        hideLoading();
    })
    .catch(error => {
        console.error('获取文档失败:', error);
        showNotification('获取文档失败: ' + error.message, 'error');
        hideLoading();
    });
}

// 显示加载中状态
function showLoading() {
    // 在这里可以添加一个加载指示器的显示逻辑
    const loadingEl = document.createElement('div');
    loadingEl.id = 'loading-indicator';
    loadingEl.className = 'loading-indicator';
    loadingEl.innerHTML = '<div class="spinner"></div><span>加载中...</span>';
    document.body.appendChild(loadingEl);
}

// 隐藏加载中状态
function hideLoading() {
    // 移除加载指示器
    const loadingEl = document.getElementById('loading-indicator');
    if (loadingEl) {
        loadingEl.remove();
    }
}

// 删除文档
async function deleteDocument(docId, event, isFromDocView) {
    if (event) {
        event.stopPropagation();
    }
    
    if (!confirm('确定要删除此文档吗？此操作不可恢复。')) {
        return;
    }
    
    try {
        const token = localStorage.getItem('token');
        if (!token) {
            showNotification('您需要登录才能删除文档');
            return;
        }
        
        const response = await fetch(`/api/document/${docId}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (response.ok) {
            showNotification('文档已成功删除', true);
            
            // 如果是从文档查看页面删除的，返回文档列表
            if (isFromDocView) {
                backToDocsList();
            }
            
            // 重新加载文档列表
            loadDocuments(window.currentKnowledgeBaseId);
        } else {
            try {
                const errorData = await response.json();
                showNotification(errorData.message || '删除文档失败');
            } catch (e) {
                showNotification('删除文档失败');
            }
        }
    } catch (error) {
        console.error('删除文档错误:', error);
        showNotification('删除文档时出错，请重试');
    }
}

// 返回知识库列表
function backToKbList() {
    // 隐藏所有panel
    document.querySelectorAll('.tab-panel').forEach(panel => {
        panel.classList.remove('active');
    });
    
    // 显示知识库panel
    document.getElementById('knowledge-tab-content').classList.add('active');
}

// 返回文档列表
function backToDocsList() {
    console.log("尝试返回文档列表");
    
    // 隐藏所有panel
    document.querySelectorAll('.tab-panel').forEach(panel => {
        panel.classList.remove('active');
    });
    
    // 显示文档列表panel
    const docsSection = document.getElementById('docs-section');
    if (docsSection) {
        docsSection.classList.add('active');
        console.log("成功切换到文档列表面板");
    } else {
        console.error("未找到文档列表面板元素");
        showNotification("无法返回文档列表", "error");
    }
    
    // 重置编辑状态
    isEditMode = false;
    currentDocumentId = null;
    
    // 清空表单内容，防止下次打开时显示旧内容
    const docTitleInput = document.getElementById('doc-title');
    if (docTitleInput) {
        docTitleInput.value = '';
    }
    
    const kbContent = document.getElementById('kb-content');
    if (kbContent) {
        kbContent.value = '';
    }
    
    resetFileUpload();
}

// 显示添加文档表单
function showAddDocumentForm() {
    // 确保不是编辑模式
    isEditMode = false;
    currentDocumentId = null;
    
    document.querySelectorAll('.tab-panel').forEach(panel => {
        panel.classList.remove('active');
    });
    
    // 显示添加文档panel
    document.getElementById('add-document-section').classList.add('active');
    
    // 设置表单标题
    document.getElementById('add-document-title').textContent = '添加文档';
    
    // 显示当前知识库名称
    const kbSelector = document.getElementById('kb-selector');
    if (window.currentKnowledgeBaseId && kbSelector) {
        const option = kbSelector.querySelector(`option[value="${window.currentKnowledgeBaseId}"]`);
        if (option) {
            currentKnowledgeBaseName = option.textContent;
            document.getElementById('current-kb-name-docs').textContent = currentKnowledgeBaseName;
        }
    }
    
    // 清空表单内容
    document.getElementById('doc-title').value = '';
    if (document.getElementById('kb-content')) {
        document.getElementById('kb-content').value = '';
    }
    resetFileUpload();
    
    // 确保按钮状态正确
    const addButton = document.getElementById('add-document-btn');
    if (addButton) {
        // 移除所有事件处理
        const newButton = addButton.cloneNode(true);
        addButton.parentNode.replaceChild(newButton, addButton);
        
        // 设置按钮文本和事件
        newButton.innerHTML = '<i class="bi bi-plus-circle"></i> 添加到知识库';
        newButton.addEventListener('click', addToKnowledgeBase);
    }
    
    // 默认切换到文本输入方式
    switchInputMethod('text');
}

// 显示创建知识库模态框
function showCreateKbModal() {
    document.getElementById('create-kb-modal').style.display = 'block';
}

// 关闭模态框
function closeModal() {
    document.getElementById('create-kb-modal').style.display = 'none';
}

// 创建知识库
async function createKnowledgeBase() {
    const name = document.getElementById('kb-name').value.trim();
    const description = document.getElementById('kb-description').value.trim();
    
    if (!name) {
        showNotification('知识库名称不能为空');
        return;
    }
    
    try {
        const token = localStorage.getItem('token');
        if (!token) {
            showNotification('您需要登录才能创建知识库');
            return;
        }
        
        const response = await fetch('/api/knowledge-base/create', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify({
                name,
                description
            })
        });
        
        if (response.ok) {
            showNotification('知识库创建成功', true);
            
            // 清空表单
            document.getElementById('kb-name').value = '';
            document.getElementById('kb-description').value = '';
            
            // 关闭模态框
            closeModal();
            
            // 重新加载知识库列表
            loadKnowledgeBases();
            
            // 重新加载知识库选择器
            loadKnowledgeBasesForSelector();
        } else {
            const errorData = await response.json();
            showNotification(errorData.message || '创建知识库失败');
        }
    } catch (error) {
        console.error('创建知识库错误:', error);
        showNotification('创建知识库时出错，请重试');
    }
}

// 添加文档到知识库
async function addToKnowledgeBase() {
    // 如果正在编辑模式，则不应该调用添加文档
    if (isEditMode && currentDocumentId) {
        console.warn("处于编辑模式，但调用了添加文档函数，应该调用更新文档");
        return updateDocument();
    }
    
    const title = document.getElementById('doc-title').value.trim();
    
    if (!title) {
        showNotification('文档标题不能为空');
        return;
    }
    
    // 禁用提交按钮，防止重复提交
    const addButton = document.getElementById('add-document-btn');
    if (addButton) {
        addButton.disabled = true;
        addButton.innerHTML = '<i class="bi bi-hourglass-split"></i> 处理中...';
    }
    
    try {
        const token = localStorage.getItem('token');
        if (!token) {
            showNotification('您需要登录才能添加文档');
            return;
        }
        
        if (currentInputMethod === 'text') {
            // 文本输入方式
            const content = document.getElementById('kb-content').value.trim();
            
            if (!content) {
                showNotification('文档内容不能为空');
                return;
            }
            
            const response = await fetch('/api/document/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    title,
                    content,
                    knowledgeBaseId: window.currentKnowledgeBaseId
                })
            });
            
            if (response.ok) {
                showNotification('文档添加成功', true);
                
                // 清空表单内容
                document.getElementById('doc-title').value = '';
                if (document.getElementById('kb-content')) {
                    document.getElementById('kb-content').value = '';
                }
                resetFileUpload();
                
                // 返回文档列表并刷新
                backToDocsList();
                loadDocuments(window.currentKnowledgeBaseId);
            } else {
                const errorData = await response.json();
                showNotification(errorData.message || '添加文档失败');
            }
        } else if (currentInputMethod === 'file') {
            // 文件上传方式
            if (!uploadedFileInfo) {
                showNotification('请先上传文件');
                return;
            }
            
            const response = await fetch('/api/document/create-from-file', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    fileInfo: uploadedFileInfo,
                    knowledgeBaseId: window.currentKnowledgeBaseId
                })
            });
            
            if (response.ok) {
                showNotification('文档添加成功', true);
                
                // 清空表单内容
                document.getElementById('doc-title').value = '';
                if (document.getElementById('kb-content')) {
                    document.getElementById('kb-content').value = '';
                }
                resetFileUpload();
                
                // 返回文档列表并刷新
                backToDocsList();
                loadDocuments(window.currentKnowledgeBaseId);
            } else {
                const errorData = await response.json();
                showNotification(errorData.message || '添加文档失败');
            }
        }
    } catch (error) {
        console.error('添加文档错误:', error);
        showNotification('添加文档时出错，请重试');
    } finally {
        // 恢复按钮状态
        if (addButton) {
            addButton.disabled = false;
            addButton.innerHTML = '<i class="bi bi-plus-circle"></i> 添加到知识库';
        }
    }
}

// 切换输入方式
function switchInputMethod(method) {
    currentInputMethod = method;
    
    // 更新UI
    document.querySelectorAll('.method-tab').forEach(tab => {
        tab.classList.toggle('active', tab.getAttribute('data-method') === method);
    });
    
    // 显示或隐藏相应的输入区域
    if (method === 'text') {
        document.getElementById('text-input-method').style.display = 'block';
        document.getElementById('file-input-method').style.display = 'none';
    } else {
        document.getElementById('text-input-method').style.display = 'none';
        document.getElementById('file-input-method').style.display = 'block';
    }
}

// 处理文件选择
async function handleFileSelected() {
    const fileInput = document.getElementById('file-upload');
    const file = fileInput.files[0];
    
    if (!file) {
        resetFileUpload();
        return;
    }
    
    // 检查文件大小限制 (默认 20MB)
    const MAX_FILE_SIZE = 20 * 1024 * 1024; // 20MB
    if (file.size > MAX_FILE_SIZE) {
        showNotification(`文件过大，请上传小于20MB的文件`);
        resetFileUpload();
        return;
    }
    
    // 检查文件类型
    const fileExt = file.name.split('.').pop().toLowerCase();
    const allowedTypes = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'md', 'markdown', 'jpg', 'jpeg', 'png', 'gif'];
    
    if (!allowedTypes.includes(fileExt)) {
        showNotification(`不支持的文件类型：${fileExt}，请上传支持的文件格式`);
        resetFileUpload();
        return;
    }
    
    // 显示文件信息
    document.getElementById('file-info').style.display = 'block';
    document.getElementById('file-name').textContent = file.name;
    document.getElementById('file-size').textContent = formatFileSize(file.size);
    
    // 隐藏文件预览区域，直到文件上传完成
    document.getElementById('file-preview-container').style.display = 'none';
    
    // 上传文件
    try {
        const token = localStorage.getItem('token');
        if (!token) {
            showNotification('您需要登录才能上传文件');
            return;
        }
        
        const formData = new FormData();
        formData.append('file', file);
        formData.append('knowledgeBaseId', window.currentKnowledgeBaseId);
        
        // 显示上传中状态
        document.getElementById('file-size').textContent = '上传中...';
        
        const response = await fetch('/api/files/upload-to-knowledge-base', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`
            },
            body: formData
        });
        
        if (response.ok) {
            const fileInfo = await response.json();
            uploadedFileInfo = fileInfo;
            
            // 更新文件大小显示
            document.getElementById('file-size').textContent = formatFileSize(file.size) + ' - 上传成功';
            
            // 如果解析出内容，显示预览
            if (fileInfo.content) {
                document.getElementById('file-preview-container').style.display = 'block';
                
                // 检查文件类型，如果是Markdown文件则使用marked解析
                const fileExt = fileInfo.originalFileName.split('.').pop().toLowerCase();
                if (['md', 'markdown'].includes(fileExt)) {
                    // 使用marked解析Markdown
                    document.getElementById('file-content-preview').innerHTML = 
                        marked.parse(fileInfo.content.substring(0, 2000)) +
                        (fileInfo.content.length > 2000 ? '<div class="text-muted">...</div>' : '');
                } else {
                    // 普通文本使用pre标签
                    document.getElementById('file-content-preview').innerHTML = 
                        `<pre>${escapeHtml(fileInfo.content.substring(0, 2000))}${fileInfo.content.length > 2000 ? '...' : ''}</pre>`;
                }
                
                // 自动设置文档标题（如果尚未设置）
                const titleInput = document.getElementById('doc-title');
                if (!titleInput.value.trim() && fileInfo.originalFileName) {
                    titleInput.value = fileInfo.originalFileName;
                }
            }
        } else {
            try {
                const errorData = await response.json();
                showNotification(errorData.message || '文件上传失败');
            } catch (e) {
                // 如果响应不是JSON格式
                showNotification('文件上传失败，服务器返回错误');
            }
            document.getElementById('file-size').textContent = formatFileSize(file.size) + ' - 上传失败';
        }
    } catch (error) {
        console.error('文件上传错误:', error);
        showNotification('文件上传时出错，请重试');
        document.getElementById('file-size').textContent = formatFileSize(file.size) + ' - 上传失败';
    }
}

// 获取支持的文件类型列表
function getSupportedFileTypes() {
    const types = [
        { ext: 'pdf', name: 'PDF文档' },
        { ext: 'doc,docx', name: 'Word文档' },
        { ext: 'xls,xlsx', name: 'Excel表格' },
        { ext: 'ppt,pptx', name: 'PowerPoint演示文稿' },
        { ext: 'txt', name: '文本文件' },
        { ext: 'md,markdown', name: 'Markdown文档' },
        { ext: 'jpg,jpeg,png,gif', name: '图片文件' }
    ];
    
    return types;
}

// 显示支持的文件类型
function showSupportedFileTypes() {
    const types = getSupportedFileTypes();
    let message = '支持的文件类型：\n';
    
    types.forEach(type => {
        message += `- ${type.name} (${type.ext})\n`;
    });
    
    message += '\n文件大小限制：20MB';
    
    alert(message);
}

// 移除已选择的文件
function removeSelectedFile() {
    resetFileUpload();
}

// 重置文件上传状态
function resetFileUpload() {
    const fileInput = document.getElementById('file-upload');
    fileInput.value = ''; // 清除文件输入
    
    document.getElementById('file-info').style.display = 'none';
    document.getElementById('file-preview-container').style.display = 'none';
    
    uploadedFileInfo = null;
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 切换Markdown预览
function togglePreview() {
    const previewContainer = document.getElementById('markdown-preview');
    
    if (previewContainer.style.display === 'none') {
        // 显示预览
        const content = document.getElementById('kb-content').value;
        const previewContent = document.querySelector('.preview-content');
        
        previewContent.innerHTML = marked.parse(content);
        previewContainer.style.display = 'block';
    } else {
        // 隐藏预览
        previewContainer.style.display = 'none';
    }
}

// 转义HTML特殊字符
function escapeHtml(unsafe) {
    return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

// 编辑文档
async function editDocument(docId, event) {
    if (event) {
        event.stopPropagation();
    }
    
    try {
        const token = localStorage.getItem('token');
        if (!token) {
            showNotification('您需要登录才能编辑文档');
            return;
        }
        
        // 清空表单，防止显示旧数据
        document.getElementById('doc-title').value = '';
        if (document.getElementById('kb-content')) {
            document.getElementById('kb-content').value = '';
        }
        resetFileUpload();
        
        const response = await fetch(`/api/document/${docId}`, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (response.ok) {
            const doc = await response.json();
            isEditMode = true;
            
            // 显示编辑表单
            document.querySelectorAll('.tab-panel').forEach(panel => {
                panel.classList.remove('active');
            });
            
            // 显示添加文档panel（编辑模式）
            document.getElementById('add-document-section').classList.add('active');
            
            // 设置表单标题
            document.getElementById('add-document-title').textContent = '编辑文档';
            document.getElementById('current-kb-name-docs').textContent = currentKnowledgeBaseName;
            
            // 保存当前编辑的文档ID
            currentDocumentId = docId;
            
            // 填充表单数据
            document.getElementById('doc-title').value = doc.title;
            
            // 根据文档类型设置输入方式
            if (doc.fileName) {
                // 文件类型文档
                switchInputMethod('file');
                
                // 显示文件信息
                document.getElementById('file-info').style.display = 'block';
                document.getElementById('file-name').textContent = doc.fileName;
                document.getElementById('file-size').textContent = '文件已上传';
                
                // 如果有内容，显示预览
                if (doc.content) {
                    document.getElementById('file-preview-container').style.display = 'block';
                    
                    // 检查文件类型，如果是Markdown文件则使用marked解析
                    const fileExt = doc.fileName.split('.').pop().toLowerCase();
                    if (['md', 'markdown'].includes(fileExt)) {
                        // 使用marked解析Markdown
                        document.getElementById('file-content-preview').innerHTML = 
                            marked.parse(doc.content.substring(0, 2000)) +
                            (doc.content.length > 2000 ? '<div class="text-muted">...</div>' : '');
                    } else {
                        // 普通文本使用pre标签
                        document.getElementById('file-content-preview').innerHTML = 
                            `<pre>${escapeHtml(doc.content.substring(0, 2000))}${doc.content.length > 2000 ? '...' : ''}</pre>`;
                    }
                }
                
                // 保存上传文件信息
                uploadedFileInfo = {
                    documentId: doc.id,
                    originalFileName: doc.fileName
                };
            } else {
                // 文本类型文档
                switchInputMethod('text');
                document.getElementById('kb-content').value = doc.content;
                
                // 重置文件上传
                resetFileUpload();
            }
            
            // 更改按钮文本和操作
            const addButton = document.getElementById('add-document-btn');
            if (addButton) {
                addButton.innerHTML = '<i class="bi bi-save"></i> 保存修改';
                
                // 移除之前的所有点击事件处理
                const newButton = addButton.cloneNode(true);
                addButton.parentNode.replaceChild(newButton, addButton);
                
                // 添加新的点击事件
                newButton.addEventListener('click', function() {
                    updateDocument();
                });
            }
        } else {
            showNotification('获取文档内容失败');
        }
    } catch (error) {
        console.error('编辑文档错误:', error);
        showNotification('编辑文档时出错，请重试');
    }
}

// 更新文档
async function updateDocument() {
    // 检查是否有当前编辑的文档ID
    if (!currentDocumentId) {
        console.error("没有当前编辑的文档ID，无法更新");
        showNotification('更新文档失败：无法确定要更新的文档');
        return;
    }

    const title = document.getElementById('doc-title').value.trim();
    
    if (!title) {
        showNotification('文档标题不能为空');
        return;
    }
    
    // 禁用提交按钮，防止重复提交
    const updateButton = document.getElementById('add-document-btn');
    if (updateButton) {
        updateButton.disabled = true;
        updateButton.innerHTML = '<i class="bi bi-hourglass-split"></i> 处理中...';
    }
    
    try {
        const token = localStorage.getItem('token');
        if (!token) {
            showNotification('您需要登录才能更新文档');
            return;
        }
        
        let response;
        
        if (currentInputMethod === 'text') {
            // 文本输入方式
            const content = document.getElementById('kb-content').value.trim();
            
            if (!content) {
                showNotification('文档内容不能为空');
                return;
            }
            
            response = await fetch(`/api/document/${currentDocumentId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    title,
                    content
                })
            });
        } else if (currentInputMethod === 'file') {
            // 文件上传方式
            if (!uploadedFileInfo) {
                showNotification('请先上传文件');
                return;
            }
            
            response = await fetch(`/api/document/update-from-file/${currentDocumentId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    title,
                    fileInfo: uploadedFileInfo
                })
            });
        }
        
        if (response.ok) {
            showNotification('文档更新成功', true);
            
            // 恢复表单标题和按钮
            document.getElementById('add-document-title').textContent = '添加文档';
            
            // 重新获取更新后的按钮引用并恢复状态
            const updateButton = document.getElementById('add-document-btn');
            if (updateButton) {
                // 移除所有现有事件处理
                const newButton = updateButton.cloneNode(true);
                updateButton.parentNode.replaceChild(newButton, updateButton);
                
                // 恢复按钮的原始状态
                newButton.innerHTML = '<i class="bi bi-plus-circle"></i> 添加到知识库';
                newButton.disabled = false;
                
                // 重新绑定添加文档功能
                newButton.addEventListener('click', addToKnowledgeBase);
            }
            
            isEditMode = false;
            currentDocumentId = null; // 重置当前编辑的文档ID
            
            // 清空表单内容
            document.getElementById('doc-title').value = '';
            if (document.getElementById('kb-content')) {
                document.getElementById('kb-content').value = '';
            }
            resetFileUpload();
            
            // 返回文档列表并刷新
            backToDocsList();
            loadDocuments(window.currentKnowledgeBaseId);
        } else {
            const errorData = await response.json();
            showNotification(errorData.message || '更新文档失败');
        }
    } catch (error) {
        console.error('更新文档错误:', error);
        showNotification('更新文档时出错，请重试');
    } finally {
        // 恢复按钮状态
        if (updateButton) {
            updateButton.disabled = false;
            updateButton.innerHTML = '<i class="bi bi-save"></i> 保存修改';
        }
    }
}

// 加载知识库选择器
async function loadKnowledgeBasesForSelector() {
    try {
        const token = localStorage.getItem('token');
        if (!token) {
            return;
        }
        
        const response = await fetch('/api/knowledge-base/list', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (response.ok) {
            const data = await response.json();
            
            // 如果页面上有知识库选择器，填充它
            const kbSelector = document.getElementById('knowledge-base-selector');
            if (kbSelector) {
                // 清空现有选项，但保留默认选项
                while (kbSelector.options.length > 1) {
                    kbSelector.remove(1);
                }
                
                // 添加知识库选项
                data.forEach(kb => {
                    const option = document.createElement('option');
                    option.value = kb.id;
                    option.textContent = kb.name;
                    kbSelector.appendChild(option);
                });
            }
        }
    } catch (error) {
        console.error('加载知识库选择器错误:', error);
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 检查是否在知识库标签页
    if (window.location.hash === '#knowledge') {
        switchToKnowledgeTab();
    }
    
    // 添加标签页切换监听
    document.querySelectorAll('.chat-tab').forEach(tab => {
        tab.addEventListener('click', function() {
            const tabName = this.getAttribute('data-tab');
            if (tabName === 'knowledge') {
                switchToKnowledgeTab();
            } else {
                switchToChatTab();
            }
        });
    });
    
    // 初始化添加文档按钮事件
    const addButton = document.getElementById('add-document-btn');
    if (addButton) {
        addButton.addEventListener('click', function() {
            addToKnowledgeBase();
        });
    }
    
    // 初始加载知识库列表
    loadKnowledgeBases();
});

// 切换到知识库标签页
function switchToKnowledgeTab() {
    // 激活标签页
    document.querySelectorAll('.chat-tab').forEach(tab => {
        tab.classList.toggle('active', tab.getAttribute('data-tab') === 'knowledge');
    });
    
    // 隐藏所有面板
    document.querySelectorAll('.tab-panel').forEach(panel => {
        panel.classList.remove('active');
    });
    
    // 显示知识库内容
    document.getElementById('knowledge-tab-content').classList.add('active');
    
    // 更新URL
    window.location.hash = 'knowledge';
    
    // 加载知识库列表
    loadKnowledgeBases();
}

// 切换到聊天标签页
function switchToChatTab() {
    // 激活标签页
    document.querySelectorAll('.chat-tab').forEach(tab => {
        tab.classList.toggle('active', tab.getAttribute('data-tab') === 'chat');
    });
    
    // 隐藏所有面板
    document.querySelectorAll('.tab-panel').forEach(panel => {
        panel.classList.remove('active');
    });
    
    // 显示聊天内容
    document.getElementById('chat-tab-content').classList.add('active');
    
    // 更新URL
    window.location.hash = 'chat';
}

// 管理知识库
function manageKnowledgeBase(kbId, event) {
    // 阻止事件冒泡
    event.stopPropagation();
    
    // 关闭所有已打开的管理菜单
    document.querySelectorAll('.kb-manage-menu').forEach(menu => {
        menu.remove();
    });
    
    // 创建悬浮菜单
    const menu = document.createElement('div');
    menu.className = 'kb-manage-menu';
    menu.innerHTML = `
        <div class="kb-menu-item" onclick="document.querySelectorAll('.kb-manage-menu').forEach(m => m.remove()); viewKnowledgeBase('${kbId}', '${currentKnowledgeBaseName}')">
            <i class="bi bi-file-earmark-text"></i>
            <span>管理文档</span>
        </div>
        <div class="kb-menu-item" onclick="document.querySelectorAll('.kb-manage-menu').forEach(m => m.remove()); editKnowledgeBase('${kbId}')">
            <i class="bi bi-pencil"></i>
            <span>编辑知识库</span>
        </div>
        <div class="kb-menu-item danger" onclick="document.querySelectorAll('.kb-manage-menu').forEach(m => m.remove()); deleteKnowledgeBase('${kbId}')">
            <i class="bi bi-trash"></i>
            <span>删除知识库</span>
        </div>
    `;
    
    // 将菜单添加到页面
    document.body.appendChild(menu);
    
    // 定位菜单到点击位置附近
    const buttonRect = event.currentTarget.getBoundingClientRect();
    menu.style.top = `${buttonRect.bottom + window.scrollY + 5}px`;
    menu.style.left = `${buttonRect.left + window.scrollX}px`;
    
    // 点击其他地方关闭菜单
    document.addEventListener('click', function closeMenu(e) {
        if (!menu.contains(e.target) && e.target !== event.currentTarget) {
            menu.remove();
            document.removeEventListener('click', closeMenu);
        }
    });
}

// 编辑知识库
function editKnowledgeBase(kbId) {
    try {
        const token = localStorage.getItem('token');
        if (!token) {
            showNotification('您需要登录才能编辑知识库');
            return;
        }
        
        // 显示加载动画
        showLoading();
        
        // 获取知识库详情
        fetch(`/api/knowledge-base/${kbId}`, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('获取知识库信息失败');
            }
            return response.json();
        })
        .then(knowledgeBase => {
            // 创建编辑模态框
            const modalHtml = `
                <div id="edit-kb-modal" class="modal">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h2>编辑知识库</h2>
                            <span class="close" onclick="closeEditModal()">&times;</span>
                        </div>
                        <div class="modal-body">
                            <div class="form-group">
                                <label for="edit-kb-name">知识库名称</label>
                                <input type="text" id="edit-kb-name" class="form-control" value="${escapeHtml(knowledgeBase.name)}" required>
                            </div>
                            <div class="form-group">
                                <label for="edit-kb-description">知识库描述</label>
                                <textarea id="edit-kb-description" class="form-control" rows="4">${escapeHtml(knowledgeBase.description || '')}</textarea>
                            </div>
                            <input type="hidden" id="edit-kb-id" value="${knowledgeBase.id}">
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn-secondary" onclick="closeEditModal()">取消</button>
                            <button type="button" class="btn-primary" onclick="updateKnowledgeBase()">保存修改</button>
                        </div>
                    </div>
                </div>
            `;
            
            // 添加到页面
            const modalContainer = document.createElement('div');
            modalContainer.innerHTML = modalHtml;
            document.body.appendChild(modalContainer.firstElementChild);
            
            // 显示模态框
            document.getElementById('edit-kb-modal').style.display = 'block';
            
            hideLoading();
        })
        .catch(error => {
            console.error('获取知识库信息失败:', error);
            showNotification('获取知识库信息失败: ' + error.message, 'error');
            hideLoading();
        });
    } catch (error) {
        console.error('编辑知识库错误:', error);
        showNotification('编辑知识库时出错，请重试', 'error');
        hideLoading();
    }
}

// 关闭编辑知识库模态框
function closeEditModal() {
    const modal = document.getElementById('edit-kb-modal');
    if (modal) {
        modal.remove();
    }
}

// 更新知识库
async function updateKnowledgeBase() {
    const kbId = document.getElementById('edit-kb-id').value;
    const name = document.getElementById('edit-kb-name').value.trim();
    const description = document.getElementById('edit-kb-description').value.trim();
    
    if (!name) {
        showNotification('知识库名称不能为空');
        return;
    }
    
    try {
        const token = localStorage.getItem('token');
        if (!token) {
            showNotification('您需要登录才能更新知识库');
            return;
        }
        
        // 显示加载动画
        showLoading();
        
        const response = await fetch(`/api/knowledge-base/${kbId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify({
                name,
                description
            })
        });
        
        if (response.ok) {
            showNotification('知识库更新成功', true);
            
            // 关闭模态框
            closeEditModal();
            
            // 重新加载知识库列表
            loadKnowledgeBases();
            
            // 重新加载知识库选择器
            loadKnowledgeBasesForSelector();
        } else {
            const errorData = await response.json();
            showNotification(errorData.message || '更新知识库失败');
        }
    } catch (error) {
        console.error('更新知识库错误:', error);
        showNotification('更新知识库时出错，请重试');
    } finally {
        hideLoading();
    }
}

// 删除知识库
function deleteKnowledgeBase(kbId) {
    if (!confirm('确定要删除此知识库吗？此操作将同时删除知识库下的所有文档，且不可恢复。')) {
        return;
    }
    
    try {
        const token = localStorage.getItem('token');
        if (!token) {
            showNotification('您需要登录才能删除知识库');
            return;
        }
        
        // 显示加载动画
        showLoading();
        
        fetch(`/api/knowledge-base/${kbId}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${token}`
            }
        })
        .then(response => {
            if (!response.ok) {
                return response.json().then(data => {
                    throw new Error(data.message || '删除知识库失败');
                });
            }
            return response.json();
        })
        .then(data => {
            showNotification('知识库删除成功', true);
            
            // 重新加载知识库列表
            loadKnowledgeBases();
            
            // 重新加载知识库选择器
            loadKnowledgeBasesForSelector();
            
            // 如果当前查看的是该知识库，返回知识库列表
            if (window.currentKnowledgeBaseId === kbId) {
                backToKbList();
            }
            
            hideLoading();
        })
        .catch(error => {
            console.error('删除知识库失败:', error);
            showNotification('删除知识库失败: ' + error.message, 'error');
            hideLoading();
        });
    } catch (error) {
        console.error('删除知识库错误:', error);
        showNotification('删除知识库时出错，请重试', 'error');
        hideLoading();
    }
}

// 打开知识库对话
function openKnowledgeBase(kbId) {
    // 切换到对话页签
    switchToChatTab();
    
    // 在知识库选择器中选择该知识库
    const kbSelector = document.getElementById('kb-selector');
    if (kbSelector) {
        kbSelector.value = kbId;
        
        // 保存当前选择的知识库ID到全局变量
        window.currentKnowledgeBaseId = kbId;
        
        // 更新输入框提示
        const input = document.getElementById('user-input');
        if (input && kbSelector.selectedIndex >= 0) {
            const kbName = kbSelector.options[kbSelector.selectedIndex].text;
            input.placeholder = `向 ${kbName} 知识库提问...`;
        }
        
        // 触发change事件
        const event = new Event('change');
        kbSelector.dispatchEvent(event);
    }
    
    // 提示用户已选择知识库
    const kbName = getKnowledgeBaseName(kbId);
    showNotification(`已选择知识库: ${kbName}`, 'success');
}

// 获取知识库名称
function getKnowledgeBaseName(kbId) {
    const kbSelector = document.getElementById('kb-selector');
    if (kbSelector) {
        const selectedOption = kbSelector.querySelector(`option[value="${kbId}"]`);
        if (selectedOption) {
            return selectedOption.textContent;
        }
    }
    return `ID: ${kbId}`;
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString();
}

// 获取相对时间字符串
function getRelativeTimeString(date) {
    const now = new Date();
    const diffInSeconds = Math.floor((now - date) / 1000);
    
    if (diffInSeconds < 60) {
        return '刚刚';
    }
    
    const diffInMinutes = Math.floor(diffInSeconds / 60);
    if (diffInMinutes < 60) {
        return `${diffInMinutes}分钟前`;
    }
    
    const diffInHours = Math.floor(diffInMinutes / 60);
    if (diffInHours < 24) {
        return `${diffInHours}小时前`;
    }
    
    const diffInDays = Math.floor(diffInHours / 24);
    if (diffInDays < 30) {
        return `${diffInDays}天前`;
    }
    
    const diffInMonths = Math.floor(diffInDays / 30);
    if (diffInMonths < 12) {
        return `${diffInMonths}个月前`;
    }
    
    const diffInYears = Math.floor(diffInMonths / 12);
    return `${diffInYears}年前`;
} 